"""
菜单权限相关API路由
"""

import logging
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_

from ...core.database import get_db
from ...core.security import get_current_user, get_current_admin_user
from ...models.user import User
from ...models.permission import MenuPermission, UserMenuPermission, RolePermission, UserRole

router = APIRouter()
logger = logging.getLogger(__name__)


@router.get("/user-menus")
async def get_user_menus(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的菜单权限"""
    try:
        # 先尝试从数据库获取菜单配置
        db_menus = db.query(MenuPermission).filter(
            and_(
                MenuPermission.is_active == True,
                MenuPermission.is_visible == True
            )
        ).order_by(MenuPermission.sort_order).all()
        
        # 如果数据库中没有菜单配置，使用默认配置
        if not db_menus:
            # 使用默认硬编码菜单配置
            base_menus = [
                {
                    "key": "dashboard",
                    "name": "仪表盘",
                    "path": "/dashboard",
                    "icon": "DataBoard",
                    "sort_order": 1,
                    "required_role": "user"
                },
                {
                    "key": "analysis",
                    "name": "AI助手",
                    "path": "/analysis",
                    "icon": "Cpu",
                    "sort_order": 2,
                    "required_role": "user"
                },
                {
                    "key": "requirements",
                    "name": "需求管理",
                    "path": "/requirements",
                    "icon": "Document",
                    "sort_order": 3,
                    "required_role": "user"
                },
                {
                    "key": "api-automation",
                    "name": "接口自动化",
                    "path": "/api-automation",
                    "icon": "Connection",
                    "sort_order": 4,
                    "required_role": "user"
                },
                {
                    "key": "ui-automation",
                    "name": "UI自动化",
                    "path": "/ui-automation",
                    "icon": "Monitor",
                    "sort_order": 5,
                    "required_role": "user"
                },
                {
                    "key": "test-tools",
                    "name": "测试工具",
                    "path": "/test-tools",
                    "icon": "Tools",
                    "sort_order": 6,
                    "required_role": "user"
                },
                {
                    "key": "user-management",
                    "name": "用户管理",
                    "path": "/user-management",
                    "icon": "User",
                    "sort_order": 7,
                    "required_role": "admin"
                }
            ]
            
            # 根据用户角色过滤菜单
            user_role = "admin" if current_user.is_admin else "user"
            accessible_menus = []
            
            for menu in base_menus:
                # 检查角色权限
                if menu["required_role"] == "admin" and not current_user.is_admin:
                    continue
                
                accessible_menus.append({
                    "key": menu["key"],
                    "name": menu["name"],
                    "path": menu["path"],
                    "icon": menu["icon"],
                    "sort_order": menu["sort_order"]
                })
        else:
            # 使用数据库中的菜单配置
            user_role = "admin" if current_user.is_admin else "user"
            accessible_menus = []
            
            for db_menu in db_menus:
                # 检查角色权限
                if db_menu.required_role == "admin" and not current_user.is_admin:
                    continue
                
                # 检查用户特定权限
                user_permission = db.query(UserMenuPermission).filter(
                    and_(
                        UserMenuPermission.user_id == current_user.id,
                        UserMenuPermission.menu_id == db_menu.id
                    )
                ).first()
                
                # 如果有明确的用户权限设置，使用该设置
                if user_permission is not None:
                    if not user_permission.is_granted:
                        continue  # 明确禁止，跳过此菜单
                
                accessible_menus.append({
                    "key": db_menu.menu_key,
                    "name": db_menu.menu_name,
                    "path": db_menu.menu_path,
                    "icon": db_menu.icon,
                    "sort_order": db_menu.sort_order
                })
        
        # 按排序顺序排列
        accessible_menus.sort(key=lambda x: x["sort_order"])
        
        return {
            "success": True,
            "data": {
                "menus": accessible_menus,
                "user_role": user_role,
                "user_id": current_user.id,
                "username": current_user.username
            }
        }
        
    except Exception as e:
        logger.error(f"获取用户菜单失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取用户菜单失败")


@router.get("/admin/menus")
async def get_all_menus(
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取所有菜单配置（仅管理员）"""
    try:
        menus = db.query(MenuPermission).order_by(MenuPermission.sort_order).all()
        
        return {
            "success": True,
            "data": {
                "menus": [
                    {
                        "id": menu.id,
                        "menu_key": menu.menu_key,
                        "menu_name": menu.menu_name,
                        "menu_path": menu.menu_path,
                        "parent_id": menu.parent_id,
                        "icon": menu.icon,
                        "sort_order": menu.sort_order,
                        "is_visible": menu.is_visible,
                        "is_active": menu.is_active,
                        "required_role": menu.required_role,
                        "required_permissions": menu.required_permissions,
                        "description": menu.description,
                        "created_at": menu.created_at,
                        "updated_at": menu.updated_at
                    }
                    for menu in menus
                ]
            }
        }
        
    except Exception as e:
        logger.error(f"获取菜单配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取菜单配置失败")


@router.post("/admin/menus")
async def create_menu(
    menu_data: dict,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """创建菜单（仅管理员）"""
    try:
        menu = MenuPermission(
            menu_key=menu_data.get("menu_key"),
            menu_name=menu_data.get("menu_name"),
            menu_path=menu_data.get("menu_path"),
            parent_id=menu_data.get("parent_id"),
            icon=menu_data.get("icon"),
            sort_order=menu_data.get("sort_order", 0),
            is_visible=menu_data.get("is_visible", True),
            is_active=menu_data.get("is_active", True),
            required_role=menu_data.get("required_role", "user"),
            required_permissions=menu_data.get("required_permissions"),
            description=menu_data.get("description")
        )
        
        db.add(menu)
        db.commit()
        db.refresh(menu)
        
        return {
            "success": True,
            "data": {
                "menu_id": menu.id,
                "message": "菜单创建成功"
            }
        }
        
    except Exception as e:
        logger.error(f"创建菜单失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="创建菜单失败")


@router.put("/admin/menus/{menu_id}")
async def update_menu(
    menu_id: int,
    menu_data: dict,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """更新菜单（仅管理员）"""
    try:
        menu = db.query(MenuPermission).filter(MenuPermission.id == menu_id).first()
        if not menu:
            raise HTTPException(status_code=404, detail="菜单不存在")
        
        # 更新菜单信息
        for field, value in menu_data.items():
            if hasattr(menu, field):
                setattr(menu, field, value)
        
        db.commit()
        
        return {
            "success": True,
            "data": {
                "message": "菜单更新成功"
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新菜单失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="更新菜单失败")


@router.delete("/admin/menus/{menu_id}")
async def delete_menu(
    menu_id: int,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """删除菜单（仅管理员）"""
    try:
        menu = db.query(MenuPermission).filter(MenuPermission.id == menu_id).first()
        if not menu:
            raise HTTPException(status_code=404, detail="菜单不存在")
        
        # 删除相关用户权限
        db.query(UserMenuPermission).filter(UserMenuPermission.menu_id == menu_id).delete()
        
        # 删除菜单
        db.delete(menu)
        db.commit()
        
        return {
            "success": True,
            "data": {
                "message": "菜单删除成功"
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除菜单失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="删除菜单失败")


@router.get("/admin/user-permissions/{user_id}")
async def get_user_permissions(
    user_id: int,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取用户权限配置（仅管理员）"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 获取所有菜单
        all_menus = db.query(MenuPermission).order_by(MenuPermission.sort_order).all()
        
        # 获取用户特定权限
        user_permissions = db.query(UserMenuPermission).filter(
            UserMenuPermission.user_id == user_id
        ).all()
        
        permission_map = {up.menu_id: up.is_granted for up in user_permissions}
        
        menu_permissions = []
        for menu in all_menus:
            menu_permissions.append({
                "menu_id": menu.id,
                "menu_key": menu.menu_key,
                "menu_name": menu.menu_name,
                "required_role": menu.required_role,
                "is_granted": permission_map.get(menu.id, None),  # None表示使用默认权限
                "default_access": menu.required_role == "user" or (menu.required_role == "admin" and user.is_admin)
            })
        
        return {
            "success": True,
            "data": {
                "user": {
                    "id": user.id,
                    "username": user.username,
                    "full_name": user.full_name,
                    "is_admin": user.is_admin
                },
                "menu_permissions": menu_permissions
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户权限失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取用户权限失败")


@router.post("/admin/user-permissions/{user_id}")
async def set_user_permissions(
    user_id: int,
    permissions_data: dict,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """设置用户权限（仅管理员）"""
    try:
        user = db.query(User).filter(User.id == user_id).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        menu_permissions = permissions_data.get("menu_permissions", [])
        
        # 删除现有权限设置
        db.query(UserMenuPermission).filter(UserMenuPermission.user_id == user_id).delete()
        
        # 创建新的权限设置
        for perm in menu_permissions:
            if perm.get("is_granted") is not None:  # 只有明确设置了权限的才保存
                user_permission = UserMenuPermission(
                    user_id=user_id,
                    menu_id=perm["menu_id"],
                    is_granted=perm["is_granted"],
                    granted_by=current_user.id
                )
                db.add(user_permission)
        
        db.commit()
        
        return {
            "success": True,
            "data": {
                "message": "用户权限设置成功"
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"设置用户权限失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="设置用户权限失败")


@router.post("/admin/init-default-menus")
async def init_default_menus(
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """初始化默认菜单配置（仅管理员）"""
    try:
        # 检查是否已经初始化
        existing_count = db.query(MenuPermission).count()
        if existing_count > 0:
            return {
                "success": True,
                "data": {
                    "message": "默认菜单已存在，无需重复初始化"
                }
            }
        
        # 默认菜单配置
        default_menus = [
            {
                "menu_key": "dashboard",
                "menu_name": "仪表盘",
                "menu_path": "/dashboard",
                "icon": "DataBoard",
                "sort_order": 1,
                "required_role": "user",
                "description": "系统仪表盘，显示统计数据和最近活动"
            },
            {
                "menu_key": "analysis",
                "menu_name": "AI助手",
                "menu_path": "/analysis",
                "icon": "Cpu",
                "sort_order": 2,
                "required_role": "user",
                "description": "AI助手：需求分析、测试用例生成等智能功能"
            },
            {
                "menu_key": "requirements",
                "menu_name": "需求管理",
                "menu_path": "/requirements",
                "icon": "Document",
                "sort_order": 3,
                "required_role": "user",
                "description": "需求项目管理"
            },

            {
                "menu_key": "api-automation",
                "menu_name": "接口自动化",
                "menu_path": "/api-automation",
                "icon": "Connection",
                "sort_order": 4,
                "required_role": "user",
                "description": "API接口自动化测试"
            },
            {
                "menu_key": "ui-automation",
                "menu_name": "UI自动化",
                "menu_path": "/ui-automation",
                "icon": "Monitor",
                "sort_order": 5,
                "required_role": "user",
                "description": "UI界面自动化测试"
            },
            {
                "menu_key": "test-tools",
                "menu_name": "测试工具",
                "menu_path": "/test-tools",
                "icon": "Tools",
                "sort_order": 6,
                "required_role": "user",
                "description": "测试工具集合"
            },
            {
                "menu_key": "user-management",
                "menu_name": "用户管理",
                "menu_path": "/user-management",
                "icon": "User",
                "sort_order": 7,
                "required_role": "admin",
                "description": "用户权限管理（仅管理员）"
            }
        ]
        
        # 创建默认菜单
        for menu_data in default_menus:
            menu = MenuPermission(**menu_data)
            db.add(menu)
        
        db.commit()
        
        return {
            "success": True,
            "data": {
                "message": f"成功初始化 {len(default_menus)} 个默认菜单"
            }
        }
        
    except Exception as e:
        logger.error(f"初始化默认菜单失败: {str(e)}")
        db.rollback()
        raise HTTPException(status_code=500, detail="初始化默认菜单失败")
